import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

df = pd.read_csv('datasets_ML2/hour.csv')

# 计算temp和atmep之间的相关系数
df1 = df[['temp', 'atemp']]
print(df1.corr())

# 底层计算pearson相关系数的2种方法
x = df1.values
print("x: ", x.shape)

plt.scatter(x[:, 0], x[:, 1])
plt.show()

# data sets
x = x - x.mean(axis=0)

m, n = x.shape

x1 = x[:, 0]
x2 = x[:, 1]

def pearsonCorr(x1, x2):
    cov_x1x2 = np.sum(x1 * x2) / m
    x1_std = np.sqrt(np.sum(x1 * x1) / m)
    x2_std = np.sqrt(np.sum(x2 * x2) / m)
    pearson_corr = cov_x1x2 / (x1_std * x2_std)
    return pearson_corr

# first way
pearson_corr = pearsonCorr(x1, x2)
print("first way: pearson_corr", pearson_corr)

# second way
C = np.dot(x.T, x) / m
pearson_corr = C[0, 1] / (np.sqrt(C[0, 0]) * np.sqrt(C[1, 1]))

print("second way: pearson_corr", pearson_corr)


# =========== add
data1 = np.random.randn(m, 2)
print(data1.shape)

plt.scatter(data1[:, 0], data1[:, 1])
plt.show()

columns = ['columns1', 'columns2']  # 横轴标签
df_data1 = pd.DataFrame(data1, columns=columns)
print(df_data1.corr())

# ============ 联合分布图
import seaborn as sns
# 使用atemp和temp绘制联合分布图
sns.jointplot(x='atemp', y='temp', data=df)
plt.show()

# 使用columns1和columns2绘制联合分布图
print(df_data1.head())

sns.jointplot(x='columns1', y='columns2', data=df_data1)
plt.show()
